package com.dindang.checkline.mvp.presenter;

import android.app.Application;
import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.dindang.checkline.R;
import com.dindang.checkline.mvp.greendao.controller.CheckItemController;
import com.dindang.checkline.mvp.greendao.entity.CheckItem;
import com.dindang.checkline.mvp.greendao.entity.CheckPiont;
import com.dindang.checkline.mvp.model.entity.BaseResponse;
import com.dindang.checkline.mvp.model.entity.CheckItemEntity;
import com.dindang.checkline.mvp.model.entity.CheckLineEntity;
import com.dindang.checkline.mvp.model.entity.LineEvent;
import com.dindang.checkline.mvp.ui.activity.CheckingActivity;
import com.dindang.checkline.mvp.ui.activity.adapter.ChooseItemAdapter;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.dindang.checkline.mvp.contract.ChooseItemContract;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.dialog.WaitDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/07/2019 13:05
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class ChooseItemPresenter extends BasePresenter<ChooseItemContract.Model, ChooseItemContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private List<CheckItem> mList = new ArrayList<>();
    private CheckItemEntity.DetailParam mParam = new CheckItemEntity.DetailParam();
    private ChooseItemAdapter mAdapter;
    private WaitDialog mWaitDialog;
    private String mState="0";
    private CheckPiont mDataPiont = new CheckPiont();
    private CheckItemEntity mData = new CheckItemEntity();
    private int total;
    private int haveCheck;
    private LineEvent mLineEvent = new LineEvent();
    @Inject
    public ChooseItemPresenter(ChooseItemContract.Model model, ChooseItemContract.View rootView) {
        super(model, rootView);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void MaintainDetailsRefresh(LineEvent lineEvent){
        getData();
    }

    public void init() {
        mWaitDialog = new WaitDialog(mRootView.getActivity());
        EventBus.getDefault().register(this);
        mDataPiont =JSON.parseObject(mRootView.getActivity().getIntent().getStringExtra("data"),CheckPiont.class);
        initAdapter();
        initListener();
        getData();
    }

    //获取巡检路线信息
    private void getData() {
        //以下是真实调接口
//        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
//        mParam.id = mDataPiont.getL_id()+"";//巡检点id
//        mModel.queryCheckItem(mParam)
//                .subscribeOn(Schedulers.io())
//                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
//                .doOnSubscribe(disposable -> {
//
//                }).subscribeOn(AndroidSchedulers.mainThread())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doFinally(() -> {
//                    从本地数据库获取列表
                    mList.clear();
                    mList.addAll(CheckItemController.selectByPiontid(mDataPiont.getlId()+""));
                    if(mList!=null){
                        setData();
                    }
//                    mWaitDialog.hideWaitingDialog();
//                })
//                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
//                .subscribe(new ErrorHandleSubscriber<BaseResponse<CheckItemEntity>>(mErrorHandler) {
//                    @Override
//                    public void onNext(BaseResponse<CheckItemEntity> response) {
//                        if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
//                            MyApplication.getInstance().gotoLoginActivity();
//                        }
//                        mData = response.getData();
//                        //数据插入本地数据库
//                        CheckItemController.deleteAllItem(mDataPiont.getL_id()+"");//插入前先删除
//                        for (int i = 0; i < mData.getItems().size(); i++) {
//                            CheckItemController.insertItem(mData.getItems().get(i));
//                        }
//                    }
//                });
    }

    private void setData() {
        mRootView.getLineName().setText("您正在巡检："+mDataPiont.getcName());
        mRootView.getLineAddress().setText("位置："+mDataPiont.getcPosition());
        total = mList.size();
        haveCheck=0;
        for (int i = 0; i < mList.size(); i++) {
            //巡检状态
            // 0未检查  1:正常  8:异常
            if(mList.get(i).getC_status().equals("1")||mList.get(i).getC_status().equals("8")){
                haveCheck++;
            }
        }
//        String[] states = {"", "等待接单", "等待开始", "正在巡检", "正常结束", "异常结束", "逾期终止", "逾期未巡", "逾期结束"};
        if(haveCheck==total){
            mRootView.getButtonGoCheck().setText("检查完毕");
        }else {
            mRootView.getButtonGoCheck().setText("已检查"+haveCheck+"/"+total);
        }
        mAdapter.notifyDataSetChanged();
    }


    /**
     * 初始化适配器
     */
    private void initAdapter() {
        mAdapter = new ChooseItemAdapter(mList);
        mRootView.getRecyclerView().setAdapter(mAdapter);
    }

    private void initListener() {
        //点击待检查的进行检查，跳转到检查中
        mAdapter.setMyOnClickListener(new ChooseItemAdapter.MyOnClickListener() {
            @Override
            public void onScanClick(int position) {
//                if(mState.equals("0")){//必须先开始
//                    Toast.makeText(mRootView.getActivity(), "请点击开始巡检", Toast.LENGTH_LONG).show();
//                }if(position!=0 && !mList.get(position-1).c_status.equals("0")){//判断是否是有序的
//                    Toast.makeText(mRootView.getActivity(), "请按顺序巡检", Toast.LENGTH_LONG).show();
//                }else{//跳转到扫面页面
                Intent intent = new Intent(mRootView.getActivity(), CheckingActivity.class);
                intent.putExtra("piontId",mDataPiont.getlId()+"");
                intent.putExtra("id",mList.get(position).getL_id()+"");
                mRootView.getActivity().startActivity(intent);
//                }
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
}
